using System;
using Castle.MonoRail.Framework.Extensions.Session;
using System.Collections;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord;
using log4net;
using FrameworkAlias = Castle.MonoRail.Framework;

namespace AgileJedi.MemcachedForMonorail.CustomSessionStateExtensions
{
	public class MemCacheSessionFactory : ICustomSessionFactory
	{
		private static bool _dbIsInitialized = false;
		private ILog _logger = LogManager.GetLogger(typeof(MemCacheSessionFactory));

		public MemCacheSessionFactory()
		{
			if (!_dbIsInitialized)
			{

				string configPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "ActiveRecord.config");
				ActiveRecordStarter.Initialize(System.Reflection.Assembly.GetAssembly(typeof(MemCacheSessionFactory)),
					 new XmlConfigurationSource(configPath));

				ActiveRecordStarter.UpdateSchema(typeof(ARSessionItem));
				_dbIsInitialized = true;
			}
		}

		#region ICustomSessionFactory Members
        IDictionary ICustomSessionFactory.ObtainSession(FrameworkAlias.IEngineContext context)
        {
            // check memcache for session            
            IDictionary session = (IDictionary)new MemCachedSessionDictionary(new Guid(context.UnderlyingContext.Session.SessionID));
            return session;
        }

        void ICustomSessionFactory.PersistSession(IDictionary session, FrameworkAlias.IEngineContext context)
        {
            if (session is MemCachedSessionDictionary)
            {
                ((MemCachedSessionDictionary)session).persistValues();
            }
        }
		#endregion
	}
}